package ph.com.gs3.formalistics.presenter.adapters;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.model.valueobjects.application.Notification;
import ph.com.gs3.formalistics.presenter.adapters.genericviewholders.BasicUserActivityViewHolder;
import ph.com.gs3.formalistics.view.valueobjects.parsers.DateUtilities;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public class NotificationListItemViewAdapter extends BaseAdapter {

	public static final String TAG = NotificationListItemViewAdapter.class.getSimpleName();

	private List<Notification> notification;
	private Context context;

	public NotificationListItemViewAdapter(Context context) {
		this.context = context;
		this.notification = new ArrayList<>();
	}

	public NotificationListItemViewAdapter(Context context, List<Notification> notification) {
		this.context = context;
		this.notification = notification;
	}

	public void setNotifications(List<Notification> notification) {

		this.notification = notification;
		notifyDataSetChanged();

	}

	@Override
	public int getCount() {
		return notification.size();
	}

	@Override
	public Object getItem(int position) {
		return notification.get(position);
	}

	@Override
	public long getItemId(int position) {
		return notification.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View row = convertView;
		BasicUserActivityViewHolder holder = null;

		Notification notification = (Notification) getItem(position);

		if (row == null) {
			LayoutInflater inflater = (LayoutInflater) context
			        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			row = inflater.inflate(R.layout.view_basic_user_activity_list_item, parent, false);

			holder = new BasicUserActivityViewHolder(row);
			row.setTag(holder);
		}

		String formattedDate = "";

		Date dateCreated;
		try {
			dateCreated = DateUtilities.parseToServerDate(notification.getDateNotified());
			if (DateUtilities.isDateToday(dateCreated)) {
				formattedDate = DateUtilities.WIDGET_DISPLAY_TIME_ONLY_FORMAT.format(dateCreated);
			} else {
				formattedDate = DateUtilities.WIDGET_DISPLAY_DATE_ONLY_FORMAT.format(dateCreated);
			}
		} catch (ParseException e) {
			e.printStackTrace();
			formattedDate = "";
		}

		holder = (BasicUserActivityViewHolder) row.getTag();

		holder.tvAuthorName.setText(notification.getNotifier().getDisplayName());
		holder.tvDateCreated.setText(formattedDate);
		holder.tvText.setText(notification.getNotificationText());

		return row;
	}

}
